﻿
namespace Leetcode.N0467.V2;

public class Solution
{
    public int FindSubstringInWraproundString(string p)
    {
        var n = p.Length;
        var maxLengths = new int[26];
        for (int fromIndex = 0; fromIndex < n; fromIndex++)
        {
            var toIndex = this.FindSubstring(p, fromIndex);
            for (int i = fromIndex; i < fromIndex + 26 && i <= toIndex; i++)
            {
                maxLengths[p[i] - 'a'] = Math.Max(maxLengths[p[i] - 'a'], toIndex - i + 1);
            }

            fromIndex = toIndex;
        }

        return maxLengths.Sum(i => i);
    }

    private int FindSubstring(string p, int fromIndex)
    {
        var toIndex = fromIndex;
        for (int i = fromIndex + 1; i < p.Length && (p[i] - p[i - 1] + 26) % 26 == 1; i++)
        {
            toIndex = i;
        }
        return toIndex;
    }
}